import './index.less'
import React, { Component } from 'react'
import { Button } from 'antd';
import { nanoid } from 'nanoid'
import { connect } from 'react-redux'
import { addPerson } from '../../redux/actions/person'
import { formateDate } from '../../dateUtils'

class Person extends Component {
    constructor(props) {
        super(props);
        this.state = {
            currentTime: formateDate(Date.now())
        }
    }
    addPerson = () => {
        const name = this.nameNode.value
        const age = this.ageNode.value * 1
        if (name !== '' && age > 0) {
            const perObj = { id: nanoid(), name, age }
            this.props.addPerson(perObj)
            this.nameNode.value = ''
            this.ageNode.value = ''
        } else {
            alert('名字和年龄输入有误！')
        }
    }

    getTime = () => {
        //每隔一秒获取当前时间,并更新状态数据currentTime
        this.intervalId = setInterval(() => {
            this.setState({
                currentTime: formateDate(Date.now())
            })
        }, 1000)
    }

    componentDidMount() {
        this.getTime()
    }

    componentWillMount() {
        clearInterval(this.intervalId)
    }

    render() {
        return (
            <div className='person'>
                <h3>{this.state.currentTime}</h3>
                <h1>Person组件,目前运算结果为：{this.props.count};</h1>
                <input ref={c => this.nameNode = c} type="text" placeholder='请输入名字' />&nbsp;
                <input ref={c => this.ageNode = c} type="text" placeholder='请输入年龄' />
                &nbsp;
                <Button onClick={this.addPerson} type='primary'>添加</Button>
                <ul>
                    {
                        this.props.person.map((p) => {
                            return <li key={p.id}><h4>名字：{p.name};&nbsp;&nbsp;年龄：{p.age};
                           &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;-----Id为：{p.id};
                            </h4></li>

                        })
                    }
                </ul>
            </div>
        )
    }
}

export default connect(
    state => ({ person: state.person, count: state.count }),
    { addPerson }
)(Person)
